<template>
	<view class="container">
		<!-- Xiaomi Style Header -->
		<view class="mi-header">
			<view class="mi-header-content">
				<view class="mi-back-btn" @click="goBack">
					<text class="mi-back-icon">‹</text>
				</view>
				<text class="mi-title">{{ isEdit ? '编辑用户' : '添加用户' }}</text>
			</view>
		</view>
		
		<!-- Content Area -->
		<scroll-view class="content-scroll" scroll-y>
			<view class="content-container">
				<!-- Form Sections -->
				<view class="form-sections">
					<!-- Basic Information Section -->
					<view class="mi-section">
						<view class="mi-section-header">
							<text class="mi-section-title">基础信息</text>
						</view>
						<view class="mi-section-content">
							<view class="mi-input-item">
								<text class="mi-input-label">用户名</text>
								<input 
									class="mi-input" 
									v-model="formData.username" 
									:disabled="isEdit"
									placeholder="请输入用户名"
								/>
							</view>
							
							<view class="mi-input-item">
								<text class="mi-input-label">{{ isEdit ? '密码 (留空不修改)' : '密码' }}</text>
								<input 
									class="mi-input" 
									v-model="formData.password" 
									type="password"
									placeholder="请输入密码"
								/>
							</view>
							
							<view class="mi-input-item">
								<text class="mi-input-label">昵称</text>
								<input 
									class="mi-input" 
									v-model="formData.nickname" 
									placeholder="请输入昵称"
								/>
							</view>
						</view>
					</view>
					
					<!-- Contact Information Section -->
					<view class="mi-section">
						<view class="mi-section-header">
							<text class="mi-section-title">联系信息</text>
						</view>
						<view class="mi-section-content">
							<view class="mi-input-item">
								<text class="mi-input-label">邮箱地址</text>
								<input 
									class="mi-input" 
									v-model="formData.email" 
									type="email"
									placeholder="请输入邮箱地址"
								/>
							</view>
							
							<view class="mi-input-item">
								<text class="mi-input-label">手机号码</text>
								<input 
									class="mi-input" 
									v-model="formData.mobile" 
									type="tel"
									placeholder="请输入手机号码"
								/>
							</view>
						</view>
					</view>
					
					<!-- Permissions Section -->
					<view class="mi-section">
						<view class="mi-section-header">
							<text class="mi-section-title">权限设置</text>
						</view>
						<view class="mi-section-content">
							<view class="mi-picker-item">
								<text class="mi-picker-label">用户角色</text>
								<picker class="mi-picker" @change="onRoleChange" :value="roleIndex" :range="roleOptions" range-key="label">
									<view class="mi-picker-content">
										<text class="mi-picker-text">{{ roleOptions[roleIndex].label }}</text>
										<text class="mi-picker-arrow">›</text>
									</view>
								</picker>
							</view>
							
							<view class="mi-picker-item">
								<text class="mi-picker-label">账户状态</text>
								<picker class="mi-picker" @change="onStatusChange" :value="statusIndex" :range="statusOptions" range-key="label">
									<view class="mi-picker-content">
										<text class="mi-picker-text">{{ statusOptions[statusIndex].label }}</text>
										<text class="mi-picker-arrow">›</text>
									</view>
								</picker>
							</view>
						</view>
					</view>
				</view>
				
				<!-- Action Buttons -->
				<view class="mi-actions">
					<view class="mi-btn mi-btn-secondary" @click="goBack">
						<text class="mi-btn-text">取消</text>
					</view>
					<view class="mi-btn mi-btn-primary" @click="saveUser" :class="{ 'disabled': saving }">
						<text class="mi-btn-text" v-if="!saving">{{ isEdit ? '保存' : '添加' }}</text>
						<view class="mi-loading" v-if="saving"></view>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			isEdit: false,
			currentUserId: '',
			saving: false,
			// Form data
			formData: {
				username: '',
				password: '',
				nickname: '',
				email: '',
				mobile: '',
				role: 'user',
				status: 'active'
			},
			roleOptions: [
				{ label: '普通用户', value: 'user' },
				{ label: '管理员', value: 'admin' }
			],
			roleIndex: 0,
			statusOptions: [
				{ label: '正常', value: 'active' },
				{ label: '禁用', value: 'disabled' }
			],
			statusIndex: 0
		}
	},
	onLoad(options) {
		// 检查权限
		this.checkPermission();
		
		// 检查是否是编辑模式
		if (options.id) {
			this.isEdit = true;
			this.currentUserId = options.id;
			this.loadEditData(options);
		}
	},
	
	methods: {
		// 权限检查
		checkPermission() {
			const userInfo = uni.getStorageSync('userInfo');
			if (!userInfo || userInfo.role !== 'admin') {
				uni.showModal({
					title: '权限不足',
					content: '只有管理员才能进行用户管理操作',
					showCancel: false,
					success: () => {
						uni.navigateBack();
					}
				});
				return;
			}
		},
		
		// 加载编辑数据
		loadEditData(options) {
			this.formData = {
				username: options.username || '',
				password: '',
				nickname: options.nickname || '',
				email: options.email || '',
				mobile: options.mobile || '',
				role: options.role || 'user',
				status: options.status || 'active'
			};
			
			// 设置选择器索引
			this.roleIndex = this.roleOptions.findIndex(item => item.value === this.formData.role);
			this.statusIndex = this.statusOptions.findIndex(item => item.value === this.formData.status);
		},
		
		// 验证表单
		validateForm() {
			if (!this.formData.username.trim()) {
				uni.showToast({
					title: '请输入用户名',
					icon: 'none'
				});
				return false;
			}
			
			if (!this.isEdit && !this.formData.password.trim()) {
				uni.showToast({
					title: '请输入密码',
					icon: 'none'
				});
				return false;
			}
			
			// 验证邮箱格式
			if (this.formData.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.formData.email)) {
				uni.showToast({
					title: '邮箱格式不正确',
					icon: 'none'
				});
				return false;
			}
			
			// 验证手机号格式
			if (this.formData.mobile && !/^1[3-9]\d{9}$/.test(this.formData.mobile)) {
				uni.showToast({
					title: '手机号格式不正确',
					icon: 'none'
				});
				return false;
			}
			
			return true;
		},
		
		// 保存用户
		async saveUser() {
			// 验证表单
			if (!this.validateForm()) {
				return;
			}
			
			this.saving = true;
			try {
				uni.showLoading({ title: this.isEdit ? '更新中...' : '添加中...' });
			
			const action = this.isEdit ? 'update' : 'create';
			const data = {
				action: action,
				userData: this.formData
			};
				
				if (this.isEdit) {
					data.userId = this.currentUserId;
					// 如果密码为空，则不更新密码
					if (!this.formData.password.trim()) {
						delete data.userData.password;
					}
				}
				
				const res = await uniCloud.callFunction({
					name: 'userManage',
					data: data
				});
				
				uni.hideLoading();
				
				if (res.result.code === 0) {
					uni.showToast({
						title: this.isEdit ? '更新成功' : '创建成功',
						icon: 'success'
					});
					
					// 延迟返回，让用户看到成功提示
					setTimeout(() => {
						this.goBack();
					}, 1500);
				} else {
					uni.showToast({
						title: res.result.message,
						icon: 'none'
					});
				}
			} catch (error) {
				uni.hideLoading();
				console.error('保存用户失败:', error);
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				});
			} finally {
				this.saving = false;
			}
		},
		
		// 角色选择变化
		onRoleChange(e) {
			this.roleIndex = e.detail.value;
			this.formData.role = this.roleOptions[this.roleIndex].value;
		},
		
		// 状态选择变化
		onStatusChange(e) {
			this.statusIndex = e.detail.value;
			this.formData.status = this.statusOptions[this.statusIndex].value;
		},
		
		// 返回上一页
		goBack() {
			uni.navigateBack();
		}
	}
}
</script>

<style scoped>
/* Xiaomi Design Color Palette */
:root {
	--mi-primary: #FF6900;
	--mi-primary-dark: #E55A00;
	--mi-primary-light: #FFE5D6;
	--mi-text-primary: #1A1A1A;
	--mi-text-secondary: #666666;
	--mi-text-tertiary: #999999;
	--mi-background: #F5F5F5;
	--mi-surface: #FFFFFF;
	--mi-border: #E5E5E5;
	--mi-divider: #F0F0F0;
	--mi-success: #34C759;
	--mi-error: #FF3B30;
}

.container {
	min-height: 100vh;
	background-color: #F5F5F5;
	display: flex;
	flex-direction: column;
}

/* Xiaomi Style Header */
.mi-header {
	background-color: #FFFFFF;
	border-bottom: 1rpx solid #E5E5E5;
	z-index: 1000;
	position: sticky;
	top: 0;
}

.mi-header-content {
	display: flex;
	align-items: center;
	padding: 0 32rpx;
	height: 88rpx;
	padding-top: 44rpx;
}

.mi-back-btn {
	width: 80rpx;
	height: 80rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 50%;
	transition: background-color 0.2s ease;
}

.mi-back-btn:active {
	background-color: #F5F5F5;
}

.mi-back-icon {
	font-size: 56rpx;
	color: #1A1A1A;
	font-weight: 300;
}

.mi-title {
	font-size: 36rpx;
	font-weight: 600;
	color: #1A1A1A;
	margin-left: 24rpx;
}

/* Content Area */
.content-scroll {
	flex: 1;
}

.content-container {
	padding: 24rpx;
}

/* Form Sections */
.form-sections {
	display: flex;
	flex-direction: column;
	gap: 24rpx;
}

.mi-section {
	background-color: #FFFFFF;
	border-radius: 24rpx;
	overflow: hidden;
	margin-bottom: 16rpx;
}

.mi-section-header {
	padding: 32rpx 32rpx 16rpx;
	border-bottom: 1rpx solid #F0F0F0;
}

.mi-section-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #1A1A1A;
}

.mi-section-content {
	padding: 24rpx 32rpx 32rpx;
}

/* Xiaomi Style Inputs */
.mi-input-item {
	margin-bottom: 32rpx;
}

.mi-input-label {
	font-size: 28rpx;
	color: #666666;
	margin-bottom: 16rpx;
	display: block;
	font-weight: 500;
}

.mi-input {
	width: 100%;
	height: 96rpx;
	padding: 0 24rpx;
	border: 2rpx solid #E5E5E5;
	border-radius: 16rpx;
	background-color: #FAFAFA;
	font-size: 30rpx;
	color: #1A1A1A;
	box-sizing: border-box;
	transition: all 0.2s ease;
}

.mi-input:focus {
	border-color: #FF6900;
	background-color: #FFFFFF;
	outline: none;
}

.mi-input:disabled {
	background-color: #F0F0F0;
	color: #999999;
	border-color: #E5E5E5;
}

.mi-input::placeholder {
	color: #CCCCCC;
	font-size: 30rpx;
}

/* Xiaomi Style Pickers */
.mi-picker-item {
	margin-bottom: 32rpx;
}

.mi-picker-label {
	font-size: 28rpx;
	color: #666666;
	margin-bottom: 16rpx;
	display: block;
	font-weight: 500;
}

.mi-picker {
	width: 100%;
	height: 96rpx;
	border: 2rpx solid #E5E5E5;
	border-radius: 16rpx;
	background-color: #FAFAFA;
	transition: all 0.2s ease;
}

.mi-picker:active {
	border-color: #FF6900;
	background-color: #FFFFFF;
}

.mi-picker-content {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 24rpx;
	height: 100%;
}

.mi-picker-text {
	font-size: 30rpx;
	color: #1A1A1A;
	flex: 1;
}

.mi-picker-arrow {
	font-size: 32rpx;
	color: #999999;
	font-weight: 300;
}

/* Xiaomi Style Action Buttons */
.mi-actions {
	display: flex;
	gap: 24rpx;
	padding: 48rpx 24rpx;
	padding-bottom: 80rpx;
}

.mi-btn {
	flex: 1;
	height: 88rpx;
	border-radius: 44rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	transition: all 0.2s ease;
	position: relative;
	overflow: hidden;
}

.mi-btn:active {
	transform: scale(0.98);
}

.mi-btn-primary {
	background-color: #FF6900;
	box-shadow: 0 4rpx 16rpx rgba(255, 105, 0, 0.3);
}

.mi-btn-primary:active {
	background-color: #E55A00;
}

.mi-btn-secondary {
	background-color: #F5F5F5;
	border: 2rpx solid #E5E5E5;
}

.mi-btn-secondary:active {
	background-color: #EEEEEE;
}

.mi-btn.disabled {
	background-color: #F0F0F0;
	pointer-events: none;
}

.mi-btn-text {
	font-size: 32rpx;
	font-weight: 600;
}

.mi-btn-primary .mi-btn-text {
	color: #FFFFFF;
}

.mi-btn-secondary .mi-btn-text {
	color: #666666;
}

.mi-btn.disabled .mi-btn-text {
	color: #CCCCCC;
}

/* Loading Animation */
.mi-loading {
	width: 40rpx;
	height: 40rpx;
	border: 4rpx solid rgba(255,255,255,0.3);
	border-top: 4rpx solid #FFFFFF;
	border-radius: 50%;
	animation: mi-spin 1s linear infinite;
}

@keyframes mi-spin {
	0% { transform: rotate(0deg); }
	100% { transform: rotate(360deg); }
}

/* Responsive Design */
@media (max-width: 750rpx) {
	.content-container {
		padding: 16rpx;
	}
	
	.mi-section-content {
		padding: 16rpx 24rpx 24rpx;
	}
	
	.mi-actions {
		padding: 32rpx 16rpx 64rpx;
	}
}

/* Dark Mode Support */
@media (prefers-color-scheme: dark) {
	.container {
		background-color: #000000;
	}
	
	.mi-header {
		background-color: #1C1C1E;
		border-bottom-color: #2C2C2E;
	}
	
	.mi-title,
	.mi-back-icon {
		color: #FFFFFF;
	}
	
	.mi-section {
		background-color: #1C1C1E;
	}
	
	.mi-section-title {
		color: #FFFFFF;
	}
	
	.mi-input-label,
	.mi-picker-label {
		color: #AEAEB2;
	}
	
	.mi-input {
		background-color: #2C2C2E;
		border-color: #3A3A3C;
		color: #FFFFFF;
	}
	
	.mi-input:focus {
		background-color: #1C1C1E;
		border-color: #FF6900;
	}
	
	.mi-picker {
		background-color: #2C2C2E;
		border-color: #3A3A3C;
	}
	
	.mi-picker-text {
		color: #FFFFFF;
	}
	
	.mi-btn-secondary {
		background-color: #2C2C2E;
		border-color: #3A3A3C;
	}
	
	.mi-btn-secondary .mi-btn-text {
		color: #AEAEB2;
	}
}
</style>